// http.c
// 网页服务器
#include "freertos/FreeRTOS.h"  // xTaskCreate
#include "esp_http_server.h"  // httpd_start
#include "esp_log.h"  // ESP_LOGI
#include "common.h"

// 暴露变量
TaskHandle_t http_handle = NULL;
// 内部变量
static const char *TAG = "HTTP";
static volatile uint32_t count = 0;  // 按下按钮的次数
// 回调函数
static esp_err_t index_handler(httpd_req_t *req) {  // 首页
  char html_response[512];
  snprintf(html_response, sizeof(html_response), 
    "<!DOCTYPE html>"
    "<html>"
    "<head>"
    "    <meta name=\"viewport\" content=\"initial-scale=1.0\">"
    "    <title>Blue Remap</title>"
    "</head>"
    "<body>"
    "    <p>按下次数:\t%lu</p>"  // 按键次数
    "    <form action='/button' method='GET'>"  // 点击按钮触发/toggle请求
    "        <button type='submit'>计数器</button>"
    "    </form>"
    "</body>"
    "</html>",
    count
  );
  return httpd_resp_send(req, html_response, HTTPD_RESP_USE_STRLEN);  // 返回网页
}
static esp_err_t button_handler(httpd_req_t *req) {  // 按钮请求
    count += 1;
    ESP_ERROR_CHECK(httpd_resp_set_status(req, "302 Found"));
    ESP_ERROR_CHECK(httpd_resp_set_hdr(req, "Location", "/"));  // 重定向到根路径
    return httpd_resp_send(req, NULL, 0);  // 发送空响应体
}
static esp_err_t favicon_handler(httpd_req_t *req) {  // 图标请求
  return httpd_resp_send(req, NULL, 0);
}

void http_task(void *arg) {
  /*--------初始化--------*/
  httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  httpd_handle_t server;
  httpd_uri_t index_uri = {  // 首页
    .uri = "/",  // 路径
    .method = HTTP_GET,  // 响应方法
    .handler = index_handler,  // 处理函数
    .user_ctx = NULL,  // 自定义参数
  };
  httpd_uri_t button_uri = {  // 按钮响应
    .uri = "/button",
    .method = HTTP_GET,
    .handler = button_handler,
    .user_ctx = NULL,
  };
  httpd_uri_t favicon_uri = {  // 图标响应
    .uri = "/favicon.ico",
    .method = HTTP_GET,
    .handler = favicon_handler,
    .user_ctx = NULL,
  };
  ESP_LOGI(TAG, "init finish.");
  /*--------网页逻辑--------*/
  while (true) {
    xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
    ESP_LOGI(TAG, "state: %s.", switch_state == 1 ? "on" : "off");
    if (switch_state == 1) {
      ESP_ERROR_CHECK(httpd_start(&server, &config));
      ESP_ERROR_CHECK(httpd_register_uri_handler(server, &index_uri));
      ESP_ERROR_CHECK(httpd_register_uri_handler(server, &button_uri));
      ESP_ERROR_CHECK(httpd_register_uri_handler(server, &favicon_uri));
      ESP_LOGI(TAG, "server started.");
    } else {
      ESP_ERROR_CHECK(httpd_unregister_uri_handler(
        server, "/", HTTP_GET)
      );
      ESP_ERROR_CHECK(httpd_unregister_uri_handler(
        server, "/button", HTTP_GET)
      );
      ESP_ERROR_CHECK(httpd_unregister_uri_handler(
        server, "/favicon.ico", HTTP_GET)
      );
      ESP_ERROR_CHECK(httpd_stop(server));
      ESP_LOGI(TAG, "server stopped.");
    }
    xTaskNotify(switch_handle, 0, eNoAction);
  }
}
